<?PHP
class Form{

  public  $id              = -1;
  public  $name            = "";
  public  $dir             = "";
  public  $fields          = array();
  public  $buttonText      = "";
  public  $type            = 1;
  public  $dataTypeID      = -1;
  public  $captcha         = false;
  public  $showAfterInsert = false;
  public  $succeedMessage  = "Das Formular wurde erfolgreich abgesendet!";
  private $dataType        = null;
  private $inserted        = false;
  private $submissionTried = false;
  private $errorMessage    = "";

  public function __construct($id){
    $this->id              = $GLOBALS['db']->EscapeString($id);
    $obj                   = $GLOBALS['db']->ReadRow("SELECT * FROM {'dbprefix'}forms WHERE id = '".$id."'");
    $this->name            = $obj->name;
    $this->dir             = $obj->dir;
    $this->destinationType = $obj->destinationType;
    $this->buttonText      = $obj->buttonText;
    $this->dataTypeID      = $obj->datatype;
    $this->captcha         = $obj->captcha;
    $this->succeedMessage  = $obj->succeedMessage;
    $this->showAfterInsert = $obj->showAfterInsert;
  }

  public function getFields(){
    if(sizeOf($this->fields) == 0){
      $this->loadFields();
    }
    return $this->fields;
  }

  public function addField(FormField $field){
    $this->fields[] = $field;
    $field->form = $this;
  }

  private function loadFields(){
      $fields = $GLOBALS['db']->ReadRows("SELECT * FROM {'dbprefix'}form_fields WHERE form = '".$this->id."' ORDER BY sortIndex");
      if($fields){
        foreach($fields as $field){
          $objField = new FormField();
          $objField->form         = $this;
          $objField->name         = $field->name;
          $objField->type         = $field->type;
          $objField->sortIndex    = $field->sortIndex;
          $objField->label        = $field->label;
          $objField->show         = $field->show;
          $objField->insert       = $field->insert;
          $objField->mandatory    = $field->mandatory;
          $objField->dataName     = $field->dataName;
          $objField->preAllocate  = $field->preallocate ;
          $objField->edit         = $field->edit;
          $objField->clear();
          $this->fields[] = $objField;
        }
      }
  }

  public function display(){
    echo $this->getCode();
  }

  public function getCode(){
    $res = "";
    if(!$this->submissionTried){
      $this->submit();
    }
    if($this->inserted){
      $res .= "<p class='success_message'>".$this->succeedMessage."</p>";
    }
    if(!$this->inserted || $this->showAfterInsert){
      $res .= $this->getErrorMessage()."<form method=\"POST\">";
      if($fields = $this->getFields()){
        foreach($fields as $field){
          if($this->inserted){
            $field->clear();
          }
          $res .= $field->getCode();
        }
      }
      $res .= "<input class=\"formsubmit\" name=\"form".$this->id."submit\" type=\"submit\" value=\"".htmlentities($this->buttonText)."\" /></form>";
    }
    return $res;
  }

  public function submit(){
    if($this->isSubmitted()){
      $values = array();
      $validate = true;
      $fields = $this->getFields();
      foreach($fields as $field){
        if($field->insert){
          $field->setValueFromArray($_POST);
          $values[] = $field->getSqlValue();
        }
        $validate = $field->validate() && $validate;
        $this->errorMessage .= $field->getLastError();
      }
      if($validate && $this->validateDataType($fields)){
        $this->inserted = $GLOBALS['db']->Execute($this->getDataType()->getInsertStatement($values,$this->getIgnoredColumns()));
      }
    }
    $this->submissionTried = true;
  }

  public function save(){
    $name           = $GLOBALS['db']->EscapeString($this->name);
    $buttonText     = $GLOBALS['db']->EscapeString($this->buttonText);
    $dataType       = $GLOBALS['db']->EscapeString($this->dataTypeID);
    $succeedMessage = $GLOBALS['db']->EscapeString($this->succeedMessage);
    if($this->captcha && $this->captcha != "off"){
      $captcha = '1';
    }
    else{
      $captcha = '0';
    }
    if(($this->showAfterInsert && $this->showAfterInsert != "off") || ($this->showAfterInsert == '1' && $this->showAfterInsert != '0')){
      $showAfterInsert = '1';
    }
    else{
      $showAfterInsert = '0';
    }
    $GLOBALS['db']->Execute("UPDATE {'dbprefix'}forms SET name = '".$name."', buttonText = '".$buttonText."',captcha = '".$captcha."',datatype='".$dataType."',succeedMessage = '".$succeedMessage."',showAfterInsert = '".$showAfterInsert."' WHERE id = '".$this->id."'");
    $this->clearFieldsFromDB();
    foreach($this->fields as $field){
      $field->save();
    }
  }

  private function clearFieldsFromDB(){
    $GLOBALS['db']->Execute("DELETE FROM {'dbprefix'}form_fields WHERE form = '".$this->id."'");
  }

  public function IsEmpty(){
    return $GLOBALS['db']->ReadField("SELECT COUNT(*) FROM {'dbprefix'}form_fields WHERE form = '".$this->id."'") == 0;
  }

  public static function create($name,$dir = ""){
    $name = $GLOBALS['db']->EscapeString($name);
    $dir = $GLOBALS['db']->EscapeString($dir);
    $res = $GLOBALS['db']->Execute("INSERT INTO {'dbprefix'}forms (name, dir) VALUES ('".$name."', '".$dir."')");
    if($res){
      $args['name']  = $name;
      EventManager::raiseEvent("form_created","../",$args);
    }
    return $GLOBALS['db']->InsertID();
  }

  public static function getAll(){
    return $GLOBALS['db']->ReadRows("SELECT * FROM {'dbprefix'}forms");
  }

  public static function getByDir($dir){
    $dir = $GLOBALS['db']->EscapeString($dir); 
    return $GLOBALS['db']->ReadRows("SELECT * FROM {'dbprefix'}forms WHERE dir = '".$dir."'");
  }

  public function getDataType(){
    if($this->dataType == null){
      $this->dataType = new DataType($this->dataTypeID);
    }
    return $this->dataType;
  }

  private function getIgnoredColumns(){
    $res = array();
    foreach($this->fields as $field){
       if(!$field->insert){
         $res[] = $field->dataName;
       }
    }
    return $res;
  }

  private function isSubmitted(){
    return isset($_POST["form".$this->id."submit"]);
  }

  private function getErrorMessage(){
    $res = "";
    if($this->errorMessage != ""){
      $res = "<p class='error_message'>".$this->errorMessage."</p>";
    }
    return $res;
  }

  private function getParams($fields){
    $res = array();
    foreach($fields as $field){
      $res[$field->dataName] = $field->getValue();
    }
    return $res;
  }

  private function validateDataType($fields){
     $res = $this->getDataType()->validate($this->getParams($fields));
     if(!$res){
       foreach($this->getDataType()->getValidatiingErrors() as $error){
         $this->errorMessage .= $error."<br />";
       }
     }
     return $res;
  }
}
?>